<?php

namespace App\Services;

use App\Models\WxMinigameLoginSession;
use YQ\YqExtend;

class WxMinigameLoginSessionService extends ServiceBase
{
    public function updateSessionKey($appid, $openid, $unionid, $session_key)
    {
        $login = WxMinigameLoginSession::whereRaw("openid='{$openid}' AND appid='{$appid}'")->first();
        if (!$login) {
            $login = new WxMinigameLoginSession;
            $login->create_time = time();
            $login->appid = $appid;
            $login->openid = $openid;
        }
        if (!empty($unionid) && empty($login->unionid)) {
            $login->unionid = $unionid;
        }

        $login->login_time = time();
        $login->session_key = $session_key;
        $login->token = YqExtend::uniqid32();
        $login->save();

        return $login;
    }

    public function getByToken($token)
    {
        return WxMinigameLoginSession::where('token', $token)->first();
    }

    public function getByOpenid($appid, $openid)
    {
        return WxMinigameLoginSession::whereRaw("openid='{$openid}' AND appid='{$appid}'")->first();
    }

    public function getByUnionid($appid, $unionid)
    {
        return WxMinigameLoginSession::whereRaw("unionid='{$unionid}' AND appid='{$appid}'")->first();
    }
}
